#-*- coding: gbk -*-
'''
Created on 2009-10-28

@author: szy
'''

"""change the content of the  files for vuscripts. """

import wx
import string
import os
import re

class CancelError(Exception):
    
    def __init__(self, value=''):
        self.value = value
    
    def __str__(self):
        
        return repr(self.value)
        

class TestPanel(wx.Panel):
    
    def __init__(self, parent):

        wx.Panel.__init__(self, parent, -1)
        
        self.PATH = ''
        
        sizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
        
        self.oldLabel = wx.StaticText(self, -1, "Old Text:")
        self.oldText = wx.TextCtrl(self, -1, "")
        self.newLabel = wx.StaticText(self, -1, "New Text:")
        self.newText = wx.TextCtrl(self, -1, "")

        self.b = wx.Button(self, -1, "Choose a directory")
        
        self.dirText = wx.TextCtrl(self, -1, "")
        self.changeButton = wx.Button(self, -1, "Change")
        
        sizer.Add(self.oldLabel)
        sizer.Add(self.oldText)
        sizer.Add(self.newLabel)
        sizer.Add(self.newText)
        sizer.Add(self.b)
        sizer.Add(self.dirText)
        sizer.Add(self.changeButton)
        
        border = wx.BoxSizer()
        border.Add(sizer, 0, wx.ALL, 20)
        self.SetSizer(border)
        
        self.Bind(wx.EVT_BUTTON, self.OnButton, self.b)
        self.Bind(wx.EVT_BUTTON, self.OnChange, self.changeButton)
        
    
    def OnButton(self, evt):
        # In this case we include a "New directory" button. 
        dlg = wx.DirDialog(self, "Choose a directory:",
                          style=wx.DD_DEFAULT_STYLE
                           #| wx.DD_DIR_MUST_EXIST
                           #| wx.DD_CHANGE_DIR
                           )

        # If the user selects OK, then we process the dialog's data.
        # This is done by getting the path data from the dialog - BEFORE
        # we destroy it. 
        if dlg.ShowModal() == wx.ID_OK:
            #print 'You selected: %s\n' % dlg.GetPath()
            path_value = dlg.GetPath()
            self.dirText.SetValue(path_value)
            self.PATH = string.replace(path_value, "\\", "\\\\")
            self.PATH = self.PATH + '\\\\'
        
        
        # Only destroy a dialog after you're done with it.
        dlg.Destroy()

    def get_max(self):
        
        max = 0

        for  root, dirs, files in os.walk(self.PATH):
            
            for filename in files:
                
                if filename.find('.c') != -1 and filename.find('.cfg') == -1:
                    
                    max = max + 1
        
        return max
    
    def OnChange(self, evt):
        
        try:
            OLD_STR = self.oldText.GetValue()
            NEW_STR = self.newText.GetValue()
            
            max = self.get_max()
            
            dlg = wx.ProgressDialog("Progress dialog example",
                                   "An informative message",
                                   maximum = max,
                                   parent=self,
                                   style = wx.PD_CAN_ABORT
                                    | wx.PD_APP_MODAL
                                    | wx.PD_ELAPSED_TIME
                                    #| wx.PD_ESTIMATED_TIME
                                    | wx.PD_REMAINING_TIME
                                    )
            
            if max == 0:
                raise CancelError()
            
            keepGoing = True
            
            #init
            count = 0     
            (keepGoing, skip) = dlg.Update(count)
            
            for  root, dirs, files in os.walk(self.PATH):
        
                for filename in files:
                    
                    if filename.find('.c') != -1 and filename.find('.cfg') == -1:
                        data = open(root+ '\\' + filename).read()
                        data.decode('gbk', 'ignore').encode('utf-8') 
                        
                        try:
                            data = re.sub(OLD_STR, NEW_STR, data)
                        except :
                            continue
                        open(root+ '\\' + filename, 'wb').write(data)
                        count = count + 1
                        (keepGoing, skip) = dlg.Update(count)
                        if not keepGoing:
                            raise CancelError()
            
            dlg.Destroy()
                    
        except CancelError, e:
            
            dlg.Destroy()
            
        

class Frame(wx.Frame):
    """Frame class """
    
    def __init__(self, parent=None, id=-1, pos=wx.DefaultPosition, title='Report'):
        
        """Create a Frame instance and display image."""
        wx.Frame.__init__(self, parent, id, title, pos, (270, 200))
        self.panel = TestPanel(self)

class App(wx.App):
    """Application class."""
    
    def OnInit(self):
        self.frame = Frame()
        ib = wx.IconBundle()
        ib.AddIconFromFile("del.ico",wx.BITMAP_TYPE_ANY)
        self.frame.SetIcons(ib)
        self.frame.Show()
        self.SetTopWindow(self.frame)
        return True

def run():
    app = App(0)
    app.MainLoop()    

def main():
    app = App(0)
    app.MainLoop()
    
if __name__ == '__main__':
    
    main()
    
    
    